package com.gexin.core.web;

import com.gexin.common.GeXinSessionKit;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.interceptor.AppInterceptor;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.wxaapp.WxaConfig;
import org.apache.commons.lang3.StringUtils;

/**
 * APP 基本的Controller
 *
 * @author 肖得明
 */
@Before(AppInterceptor.class)//统一错误拦截
public class AppController extends Controller {

	@NotAction
	public String getWxappId() {
		String appid = getHeader("wxa_appid");//暂时放是
		if (StringUtils.isEmpty(appid)) {
			appid = "wxdb4a18fe5731ee4a";
		}
		return appid;
	}

	public WxaConfig  getWxaConfig(){
		return WeixinAppConfig.dao.findFirst("SELECT * from t_weixin_app_config where app_id=?",getWxappId()).getWxaConfigs();
	}
	public Boolean isXapp() {
		return "xapp".equals(getHeader("source"));
	}

	//活动当前登录用户的openID  sessionId换openID
	@NotAction
	private String getAuthOpenid() {
		String sessionJson = GeXinSessionKit.getSession(getHeader("user-token"));
		ApiResult sessionResult = ApiResult.create(sessionJson);
		String openid = sessionResult.get("openid");
		return openid;
	}

	/**
	 * 返回当前登录用户的信息
	 */
	@NotAction
	public WeixinUser getAuthUser() {
		if (isXapp()) {
			return WeixinUser.dao.getUserByOpentId(getAuthOpenid());
		} else {
			if(WeixinUser.dao.findById(getAttr("user_id"))==null){
				return WeixinUser.dao.findById(getHeader("user-id"));
			}else{
				return WeixinUser.dao.findById(getAttr("user_id"));
			}
		}
	}

	/**
	 * 返回当前登录用户的信息的主键ID
	 */
	@NotAction
	public Integer getAuthUserId() {
		if(getAuthUser()==null){
			return null;
		}
		return getAuthUser().getId();
	}

	/**
	 * 判断是否是ajax
	 *
	 * @return
	 */
	@NotAction
	public boolean isAjax() {
		String requtype = getRequest().getHeader("X-Requested-With");
		if (StringUtil.isNotBlank(requtype)) {
			if (requtype.equals("XMLHttpRequest")) {
				return true;
			}
		}
		return false;
	}

	@NotAction
	public void success() {
		renderJson(new AjaxCmd(true));
	}

	@NotAction
	public void success(Object data) {
		renderJson(new AjaxCmd(data));
	}

	@NotAction

	public void success(String msg) {
		renderJson(new AjaxCmd(true, msg));
	}

	@NotAction
	public void fail() {
		renderJson(new AjaxCmd(false));
	}

	@NotAction
	public void fail(String msg) {
		renderJson(new AjaxCmd(false, msg));
	}

	/**
	 * 获取页码  默认从0开始
	 *
	 * @return
	 */
	@NotAction
	public int getPageIndex() {
		return getParaToInt("page", 1);
	}

	/**
	 * 获取每页显示大小
	 *
	 * @return
	 */
	@NotAction
	public int getPageSize() {
		return getParaToInt("size", 10);
	}
}
